package saxon.gui.model.xml;

import com.google.common.collect.Lists;
import java.io.File;
import java.util.List;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathExecutable;
import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmValue;

/**
 *
 * @author lennyn
 */
public class XPathHelper implements XmlHelper {

	private final static Processor processor = new Processor(false);
	private final static DocumentBuilder docBuilder = processor.newDocumentBuilder();
	private final static XPathCompiler compiler = processor.newXPathCompiler();
	private final XPathExecutable executable;

	public XPathHelper(String query, String defaultNS) throws Exception {
		compiler.declareNamespace("", defaultNS);
		compiler.setLanguageVersion("2.0");
		compiler.declareVariable(new QName("__FILE__"));
		executable = compiler.compile(query);
	}

	@Override
	public XdmValue execute(File srcFile) throws Exception {
		XPathSelector selector = executable.load();
		try {
			selector.setContextItem(docBuilder.build(srcFile));
			selector.setVariable(
					new QName("__FILE__"),
					new XdmAtomicValue(srcFile.getCanonicalPath()));
			return selector.evaluate();
		}
		catch (SaxonApiException ex) {
			throw new XException(ex);
		}
	}

	List<String> executeAndGetString(File srcFile) throws Exception {
		List<String> res = Lists.newArrayList();
		for (XdmItem item : execute(srcFile)) {
			res.add(item.toString());
		}
		return res;
	}
}
